package com.authority.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.authority.OpServiceException;
import com.authority.common.AdminConstants;
import com.authority.common.MD5Util;
import com.authority.common.UserTypeEnum;
import com.authority.entry.AuthSysDO;
import com.authority.entry.AuthUserDO;
import com.authority.entry.AuthUserRoleDO;
import com.authority.query.UserQuery;
import com.authority.result.PageResult;
import com.authority.result.UserPrivilegeDTO;
import com.authority.service.AuthSysService;
import com.authority.service.UserPrivilegeService;
import com.authority.service.UserService;
import com.authority.utils.CommonUtils;
import com.authority.utils.TokenUtils;
import com.authority.vo.AuthUserVO;
import com.authority.vo.LoginVO;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.suixun.util.Constant;


@Controller
@RequestMapping(value = "/userManager")
public class UserManager extends BaseManager {
	@Resource
	private UserService userService;

	@Resource
	private UserPrivilegeService userPrivilegeService;

	@Resource
	private HttpSession session;

	@Resource
	private AuthSysService authSysService;

	/**
	 * 用户管理---查询
	 *
	 * @param id
	 * @param organ
	 * @param workNumber
	 * @param userName
	 * @param tel
	 * @param status
	 * @return
	 */
	
	@RequestMapping(value = "/queryUser.json")
	@ResponseBody
	public Object doQueryUserList(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		PageResult<AuthUserDO> result = new PageResult<AuthUserDO>();
		if (param == null)
			param = "{index:1}";
		try {
			UserQuery query = new Gson().fromJson(param, UserQuery.class);
			AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
			if(null!=sys){
				query.setSysId(sys.getId());
			}
			if (!isAdmin()) {
				query.setNotAdmin(true);
				query.setId(getUserId());
			}
			result = userService.queryUserListPage(query);
		} catch (Exception e) {
			e.printStackTrace();
			logger("UserManager doQueryUserList:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
		return result;
	}
	
	/**
	 * <p>Title: getUser</p>
	 * <p> 功能描述:获取指定用户信息 </p>
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/getUser.json")
	@ResponseBody
	public Object getUser(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			AuthUserVO query = checkParam(param, AuthUserVO.class);
			if (query.getId() == null) {
				return fail("必要参数为空");
			}
			boolean checkAuthority = false;
			if (getUserType(query.getId()) == UserTypeEnum.REGIONMAN.getType()) {
				checkAuthority = true;
			}
			return success(userService.queryUserById(query.getId(), checkAuthority));
		} catch (Exception e) {
			logger("UserManager getUser:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}

	
	/**
	 * 新增账户
	 *
	 * @param id
	 * @param organId
	 * @param workNumber
	 * @param userName
	 * @param tel
	 * @param status
	 * @return
	 */
	
	@RequestMapping(value = "/addUser.json")
	@ResponseBody
	public Object doAddUser(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			AuthUserVO db = checkParam(param, AuthUserVO.class);
			db.setType(UserTypeEnum.GENERAL.getType());
			db.setOperatorId(getUserId());
			db.setOperatorName(getUsername());
			String res = userService.insertUser(db);
			if(!Constant.SUCCESS.equals(res)){
				return fail(res);
			}
		} catch (Exception e) {
			if (e instanceof OpServiceException) {
				return fail(e.getMessage());
			}else {
				logger("UserManager addUser:"+e.getMessage(),e);
				return fail(Constant.EXCEPTION.OPERATE_FAIL);
			}
		}
		return success(AdminConstants.CODE_STATUS_SUCCESS);
	}
	
	
	/**
	 * 修改账户
	 *
	 * @param id
	 * @param organId
	 * @param workNumber
	 * @param userName
	 * @param tel
	 * @param status
	 * @return
	 */
	
	@RequestMapping(value = "/updateUser.json")
	@ResponseBody
	public Object updateUser(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			AuthUserVO db = checkParam(param, AuthUserVO.class);
			if (!isAdmin()) {
				db.setNotAdmin(true);
			}
			db.setOperatorId(getUserId());
			db.setOperatorName(getUsername());
			String res = userService.updateUser(db);
			if(!Constant.SUCCESS.equals(res)) {
				 return fail(res);
			}
		} catch (Exception e) {
			if (e instanceof OpServiceException) {
				return fail(e.getMessage());
			}else {
				logger("UserManager updateUser:"+e.getMessage(),e);
				return fail(Constant.EXCEPTION.OPERATE_FAIL);
			}
		}
		return success();
	}
	
	/**
	 * <p>Title: deleteUser</p>
	 * <p> 功能描述:删除用户 </p>
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/deleteUser.json")
	@ResponseBody
	public Object deleteUser(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			AuthUserVO db = checkParam(param, AuthUserVO.class);
			if (db.getId() == null) {
				return fail("用户不能为空");
			}
			boolean checkAuthority = false;
			if (getUserType(db.getId()) == UserTypeEnum.REGIONMAN.getType()) {
				checkAuthority = true;
			}
			String res = userService.deleteUser(db.getId(), getUserId(), checkAuthority);
			if(Constant.SUCCESS.equals(res)) {
				 return success();
			}else {
				return fail(res);
			}
		} catch (Exception e) {
			logger("UserManager deleteUser:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	
	
	/**
	 * <p>Title: getNewWorkNumber</p>
	 * <p> 功能描述: </p>
	 * @param param
	 * @return
	 */
	
	@RequestMapping(value = "/getNewWorkNumber.json")
	@ResponseBody
	public Object getNewWorkNumber(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			AuthUserVO db = checkParam(param, AuthUserVO.class);
			Integer res = userService.getNewWorkNumber(db);
			if ("-1".equals(String.valueOf(res))) {
				return fail("组织id不能为空");
			}
			Map<String,Object> map = new HashMap<>();
			map.put("newWorkNumber", res);
			return success(map);
		} catch (Exception e) {
			logger("UserManager getNewWorkNumber:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	@RequestMapping(value = "/resetPassword")
	@ResponseBody
	public Object resetPassword(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null)
			param = "";
		try {
			AuthUserDO db = new Gson().fromJson(param, AuthUserDO.class);
			db.setType(UserTypeEnum.GENERAL.getType());
			db.setOperatorId(getUserId());
			if (null != db.getId()) {
				if (!isAdmin()) {
					if (!String.valueOf(db.getId()).equals(String.valueOf(getUserId()))) {
						return fail("您没有权限");
					}
				}
				db.setPassword(MD5Util.doubleMD5("123456"));
				userService.updatePasswordById(db);
			}else {
				return fail("重置失败");
			} 
		} catch (Exception e) {
			logger("UserManager resetPassword:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
		return success();
	}
	
	@RequestMapping(value = "/changePassword")
	@ResponseBody
	public Object changePassword(String param) {
		if (param == null)
			param = "";
		try {
			AuthUserDO db = new Gson().fromJson(param, AuthUserDO.class);
			if(db==null || db.getWorkNumber()==null || db.getWorkNumber().trim().equals(""))
				return fail("原密码不能为空");
			if(session==null || session.getAttribute("user_account")==null || session.getAttribute("user_account").toString().trim().equals(""))
				return fail("用户未登录");
			LoginVO vo = userService.login(session.getAttribute("user_account").toString().trim(), db.getWorkNumber().trim());
			if(vo==null)
				return fail("原密码验证失败");
			db.setAccount(session.getAttribute("user_account").toString().trim());
			db.setPassword(MD5Util.doubleMD5(db.getPassword()));
			userService.updatePasswordByAccount(db);
		} catch (Exception e) {
			logger("UserManager changePassword:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
		return success(AdminConstants.CODE_STATUS_SUCCESS);
	}

	/**
	 * 用户登录
	 *
	 * @param account
	 * @param password
	 * @param warehouseId
	 * @param warehouseName
	 * @return
	 */
	
	@RequestMapping(value = "/login.json")
	@ResponseBody
	public Object doLogin( String account,String password) {

		try {
			checkParams(account, password);

			LoginVO vo = userService.login(account, password);

			List<UserPrivilegeDTO> privileges = Lists.newArrayList();
			if (vo.getType().equals(UserTypeEnum.ADMIN.getType())) {
				privileges = userPrivilegeService.getAllUserPrivilegeList(); // 超级管理员权限
			} else {
				privileges = userPrivilegeService.getUserPrivilegeList(vo.getId(), AdminConstants.SYSTEM_CODE); // 普通用户权限
			}

			if (privileges != null && privileges.size() > 0) {
				vo.setPrivileges(privileges);
				Set<String> set = userPrivilegeService.getUserPrivilegeUrls(privileges);
				session.setAttribute("userPrivilegeUrls", CommonUtils.setToString(set));
			}
			userService.updateUserLastLoginTime(vo.getId());
			session.setAttribute("token",
					TokenUtils.generateToken(vo.getId().toString(), vo.getAccount(), vo.getType().toString()));
			session.setAttribute("username", vo.getUserName());
			session.setAttribute("user_account", vo.getAccount());
			logger.info("user {} login",vo.getAccount());
			logger.info("get privilege list:{}",privileges);
			
			
			return success(vo);
		} catch (Exception e) {
			logger("UserManager doLogin:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 用户登录
	 *
	 * @param account
	 * @param password
	 * @param warehouseId
	 * @param warehouseName
	 * @return
	 */
	
	@RequestMapping(value = "/loginService.json")
	@ResponseBody
	public Object doLogin( String param) {
		if(param==null)
			return fail("参数为空");
		
		try {
			AuthUserDO paramForm = new Gson().fromJson(param, AuthUserDO.class);
			LoginVO vo = userService.login(paramForm.getAccount(), paramForm.getPassword());
			List<UserPrivilegeDTO> privileges = Lists.newArrayList();
			if (UserTypeEnum.ADMIN.getType().equals(vo.getType())) {
				privileges = userPrivilegeService.getAllUserPrivilegeList(); // 超级管理员权限
			} else {
				privileges = userPrivilegeService.getUserPrivilegeList(vo.getId(), AdminConstants.SYSTEM_CODE); // 普通用户权限
			}
			if (privileges != null && privileges.size() > 0) {
				vo.setPrivileges(privileges);
				Set<String> set = userPrivilegeService.getUserPrivilegeUrls(privileges);
				session.setAttribute("userPrivilegeUrls", CommonUtils.setToString(set));
				session.setAttribute("privileges_", privileges);
			}
			userService.updateUserLastLoginTime(vo.getId());
			userService.updateUserLastLoginIp(vo.getId(), request);
			session.setAttribute("token",
					TokenUtils.generateToken(vo.getId().toString(), vo.getAccount(), vo.getType().toString()));
			session.setAttribute("username", vo.getUserName());
			session.setAttribute("usertype_", vo.getType());
			session.setAttribute("user_account", vo.getAccount());
			logger.info("user {} login",vo.getAccount());
			logger.info("get privilege list:{}",privileges);
			return success(vo);
		} catch (Exception e) {
			logger("UserManager doLogin:"+e.getMessage(),e);
			if (e instanceof OpServiceException) {
				return fail(e.getMessage());
			}else {
				return fail(Constant.EXCEPTION.OPERATE_FAIL);
			}
		}
	}

	/**
	 * 登出
	 *
	 * @return
	 */
	@RequestMapping(value = "/logout.json")
	@ResponseBody
	public Object doLogout() {

		try {
			session.invalidate();
			return success();
		} catch (Exception e) {
			logger("UserManager doCheckActionPrivilege:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
		
	}

	/**
	 * 检查功能权限
	 *
	 * @param userId
	 * @param menuCode
	 * @param actionCode
	 * @return
	 */
	@RequestMapping(value = "/checkActionPrivilege.json")
	@ResponseBody
	public Object doCheckActionPrivilege(String pageCode,String actionCode) {
		try {
			if (getType().equals(UserTypeEnum.ADMIN.getType())) {
				return success(true);
			} else {
				return success(userPrivilegeService.checkActionPrivilege(getUserId(), AdminConstants.SYSTEM_CODE,
						pageCode, actionCode));
			}
		} catch (Exception e) {
			logger("UserManager doCheckActionPrivilege:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	
	public Object doCheckPagePrivilege(String pageCode){
		try {
			if (getType().equals(UserTypeEnum.ADMIN.getType())) {
				return success(true);
			} else {
				return success(userPrivilegeService.checkPagePrivilege(getUserId(), AdminConstants.SYSTEM_CODE,pageCode));
			}
		} catch (Exception e) {
			logger("UserManager doCheckPagePrivilege:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 获取用户菜单权限
	 *
	 * @param account
	 * @param password
	 * @param warehouseId
	 * @param warehouseName
	 * @return
	 */
	
	@RequestMapping(value = "/getMenu")
	@ResponseBody
	public Object getMenu() {

		try {
			if(session.getAttribute("privileges_")==null)
				return fail("");
			List<UserPrivilegeDTO> privileges=(List<UserPrivilegeDTO>)session.getAttribute("privileges_");
			List<String> list=Lists.newArrayList();
			return success(privileges);
		} catch (Exception e) {
			logger("UserManager getMenu:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	@RequestMapping(value = "/updateUserRole.json")
	@ResponseBody
	public Object updateUserRole(String param) {
		
		if (param == null)
			param = "";
		try {
			AuthUserDO db = new Gson().fromJson(param, AuthUserDO.class);

			if (null != db.getId()) {
				AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
				userService.updateUserRole(db,sys.getId());
			}
		} catch (Exception e) {
			logger("UserManager updateUserRole:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
		return success(AdminConstants.CODE_STATUS_SUCCESS);
	}
	
	@RequestMapping(value = "/getUserRole.json")
	@ResponseBody
	public Object getUserRole(String param) {
		
		if (param == null)
			param = "";
		String roleids="";
		try {
			AuthUserDO db = new Gson().fromJson(param, AuthUserDO.class);
			if (null != db.getId()) {
				AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
				List<AuthUserRoleDO> roles=userService.getUserRole(db,sys.getId());
				
				for(int i=0;i<roles.size();i++) {
					roleids+=roles.get(i).getRoleId()+",";
				}
			}
		} catch (Exception e) {
			logger("UserManager getUserRole:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
		if(roleids.indexOf(",")>-1)
			roleids=roleids.substring(0,roleids.length()-1);
		return success(roleids);
	}
	
	@RequestMapping(value = "/getUserName")
	@ResponseBody
	public Object getUserName(String param) {
		
		String username=session.getAttribute("username")!=null?session.getAttribute("username").toString():null;
		
		return success(username);
	}
}
